package com.fractalist.base.core.web.interceptor;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.nutz.json.Json;
import org.springframework.beans.factory.annotation.Autowired;

import com.fractalist.man.base.SqlUtils;
import com.fractalist.man.service.IScoreRuleService;
import com.fractalist.man.service.IScoreService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * 积分的拦截器，每次通过action的名称进行拦截
 * 
 * @author radio
 * 
 */
public class ScoreInterceptor implements Interceptor {

	private static final long serialVersionUID = 1L;

	private static final Logger logger = Logger.getLogger("R");

	public void init() {

	}

	@Autowired
	private IScoreRuleService scoreRuleService;
	@Autowired
	private IScoreService scoreService;

	@SuppressWarnings("unchecked")
	public String intercept(ActionInvocation invocation) throws Exception {
		ActionContext ac = invocation.getInvocationContext();
		HttpServletRequest request = (HttpServletRequest) ac
				.get(ServletActionContext.HTTP_REQUEST);
		// 获取请求的action名称
		String actionName = ac.getName();
		// System.out.println(actionName);
		// System.out.println(parameters);
		// ActionSupport action = (ActionSupport) invocation.getAction();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("action", actionName);
		Map<String, Object> rule = scoreRuleService.queryOneRowFromDbOrCache(
				SqlUtils.genderQuerySql("man_base_score_rule",
						SqlUtils.genderConditionsByType(paramMap, "and")),
				"5mn");
		if (rule != null && rule.size() > 0) {
			// 获取action后附带参数
			Map<String, Object> parameters = (Map<String, Object>) ((Map<String, Object>) ac
					.getParameters()).get("paramMap");
			if (parameters.get("curUserId") != null) {
				Long curUserId = Long.valueOf(parameters.get("curUserId") + "");
				BigDecimal addScore = (BigDecimal) rule.get("score");
				if (!scoreService.addScore(curUserId, addScore,
						(Long) rule.get("id"))) {
					logger.debug("日志积分操作失败，当前参数为>  actionName:" + actionName
							+ " curUserId:" + curUserId + ",rule:"
							+ Json.toJson(rule));
				}
			}
		}
		String result = invocation.invoke();
		return result;

	}

	public void destroy() {
		// TODO Auto-generated method stub

	}
}
